package marking.liu.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 自定义Redis序列化
 */
@Configuration
public class RedisCacheConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
//        1、构建RedisTemplate模板对象
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
//        2、为不同的数据结构设置不同的序列方案
//        设置key序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        设置value序列化方式
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
//        设置hash中field字段序列化方式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//        设置hash中value字段的序列化方式
        redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
//        3、初始化参数设置
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
